import React from "react";
import PropTypes from 'prop-types'
import {padLeft,range} from "../utility";

class MonthPicker extends React.Component{

  constructor(props) {
    super(props);
    this.state={
      isOpen: false,
      selectedYear:this.props.year
    }
  }

  toggleDropdown = (event)=>{
    event.preventDefault()
    this.setState({
      isOpen: !this.state.isOpen
      }
    )
  }

  selectYear=(event,yearNumber)=>{
     event.preventDefault();
     this.setState(
       {
         selectedYear:yearNumber
       }
     )
  }

  selectMonth = (event,monthNumber)=>{
    event.preventDefault();
    //关闭下拉菜单
    this.setState(
      {
        isOpen: false
      }
    );
    //将Year和month传递出去,凡是和props里面的函数或者变量打交道的基本都和外界组件有交互
    this.props.onChange(
      this.state.selectedYear,monthNumber
    );
  }
  render() {
    const {year,month} = this.props
    const {selectedYear,isOpen} = this.state
    const monthRange = range(12,1)
    const yearRange = range(9,-4).map(number=>number+year)
    const TimeClassName = (currenttime,time_view)=>{
      return (currenttime=== time_view)? 'dropdown-item active' : 'dropdown-item'
    }

    return(
      <div className="dropdown month-picker-component">
        <h4>选择月份 </h4>
        {/*https://getbootstrap.com/docs/4.0/components/buttons/*/}
        {/*https://getbootstrap.com/docs/4.0/components/dropdowns/*/}
         <button className="btn btn-lg btn-secondary dropdown-toggle"
                 onClick={this.toggleDropdown}
         >
           {`${year}年 ${padLeft(month)}月`}
         </button>
        {
          isOpen &&
            <div className="dropdown-menu" style={{display:'block'}}>
              <div className="row">
                <div className="col border-right">
                  {
                    yearRange.map((yearNumber,index)=>(
                      <a key={index}
                         href="#"
                         onClick={(event)=>{this.selectYear(event,yearNumber)}}
                         className={TimeClassName(yearNumber,selectedYear)}>
                        {yearNumber}年
                      </a>
                    ))
                  }
                </div>
                <div className="col">
                  {
                    monthRange.map((monthNumber,index)=>(
                      <a key={index}
                         href="#"
                         onClick={(event)=>{this.selectMonth(event,monthNumber)}}
                         className={TimeClassName(monthNumber,month)}>
                        {padLeft(monthNumber)}月
                      </a>
                    ))
                  }
                </div>
              </div>
            </div>
        }
      </div>
    )
  }
}

MonthPicker.propTypes = {
  year: PropTypes.number.isRequired,
  month:PropTypes.number.isRequired,
  onChange:PropTypes.func.isRequired
}


export default MonthPicker